#!/bin/bash

# 脚本名称：NAS-Tools 一键部署脚本
# 作者：Eric
# 功能：自动部署Jackett、Qbittorrent、NAS-Tools，自动获取当前用户ID

# 检查是否为bash环境（避免sh执行导致的兼容性问题）
if [ -z "$BASH_VERSION" ]; then
    echo "错误：请使用bash执行此脚本（而非sh）"
    exit 1
fi

# --- 定义默认变量 ---
DEFAULT_JACKETT_PORT=9117
DEFAULT_QBITTORRENT_WEBUI_PORT=8080
DEFAULT_NASTOOLS_PORT=3000
COMPOSE_FILE="$PWD/docker-compose.yml"

# 清屏并显示标题（提升视觉体验）
clear
echo "========================================="
echo "  多服务一键部署脚本 - 自动获取用户ID版"
echo "========================================="
echo "  部署服务：Jackett、Qbittorrent、NAS-Tools"
echo "========================================="
sleep 1

# 脚本所在目录（确保路径正确解析）
DEPLOY_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
DOCKER_BASE_DIR="$DEPLOY_DIR/docker"
MEDIA_BASE_DIR="$DEPLOY_DIR/media"

# 检查Docker是否安装
if ! command -v docker &>/dev/null; then
    echo "错误：未检测到Docker，请先安装Docker"
    exit 1
fi

# --- 交互式输入 ---

# 1. 端口映射（增加端口占用检测）
check_port() {
    local port=$1
    if ss -tuln | grep -q ":$port "; then
        echo "警告：端口 $port 已被占用"
        return 1
    fi
    return 0
}

read -p "请输入 Jackett 宿主机端口 [默认: $DEFAULT_JACKETT_PORT]: " JACKETT_PORT
JACKETT_PORT=${JACKETT_PORT:-$DEFAULT_JACKETT_PORT}
while ! [[ "$JACKETT_PORT" =~ ^[0-9]+$ ]] || ! check_port "$JACKETT_PORT"; do
    if ! [[ "$JACKETT_PORT" =~ ^[0-9]+$ ]]; then
        read -p "端口必须是数字，请重新输入: " JACKETT_PORT
    else
        read -p "端口 $JACKETT_PORT 已被占用，请重新输入: " JACKETT_PORT
    fi
done

read -p "请输入 Qbittorrent WebUI 端口 [默认: $DEFAULT_QBITTORRENT_WEBUI_PORT]: " QBITTORRENT_WEBUI_PORT
QBITTORRENT_WEBUI_PORT=${QBITTORRENT_WEBUI_PORT:-$DEFAULT_QBITTORRENT_WEBUI_PORT}
while ! [[ "$QBITTORRENT_WEBUI_PORT" =~ ^[0-9]+$ ]] || ! check_port "$QBITTORRENT_WEBUI_PORT"; do
    if ! [[ "$QBITTORRENT_WEBUI_PORT" =~ ^[0-9]+$ ]]; then
        read -p "端口必须是数字，请重新输入: " QBITTORRENT_WEBUI_PORT
    else
        read -p "端口 $QBITTORRENT_WEBUI_PORT 已被占用，请重新输入: " QBITTORRENT_WEBUI_PORT
    fi
done

read -p "请输入 NASTOOLS 端口 [默认: $DEFAULT_NASTOOLS_PORT]: " NASTOOLS_PORT
NASTOOLS_PORT=${NASTOOLS_PORT:-$DEFAULT_NASTOOLS_PORT}
while ! [[ "$NASTOOLS_PORT" =~ ^[0-9]+$ ]] || ! check_port "$NASTOOLS_PORT"; do
    if ! [[ "$NASTOOLS_PORT" =~ ^[0-9]+$ ]]; then
        read -p "端口必须是数字，请重新输入: " NASTOOLS_PORT
    else
        read -p "端口 $NASTOOLS_PORT 已被占用，请重新输入: " NASTOOLS_PORT
    fi
done

# 2. 获取并验证PUID/PGID（增加错误处理）
echo -e "\n--- 自动获取当前用户ID ---"
if ! CURRENT_PUID=$(id -u 2>/dev/null); then
    echo "错误：无法获取当前用户PUID"
    exit 1
fi
if ! CURRENT_PGID=$(id -g 2>/dev/null); then
    echo "错误：无法获取当前用户PGID"
    exit 1
fi

echo "当前登录用户的ID："
echo "  PUID: $CURRENT_PUID"
echo "  PGID: $CURRENT_PGID"
echo "（直接回车将使用以上值，无需手动输入）"

read -p "请输入 PUID（默认: $CURRENT_PUID）: " PUID
PUID=${PUID:-$CURRENT_PUID}
while ! [[ "$PUID" =~ ^[0-9]+$ ]]; do
    read -p "PUID必须是数字，请重新输入: " PUID
done

read -p "请输入 PGID（默认: $CURRENT_PGID）: " PGID
PGID=${PGID:-$CURRENT_PGID}
while ! [[ "$PGID" =~ ^[0-9]+$ ]]; do
    read -p "PGID必须是数字，请重新输入: " PGID
done

# --- 部署步骤 ---

echo -e "\n========================================="
echo "         正在部署服务..."
echo "========================================="

# 创建所需目录（增加权限检查）
dirs=(
    "$DOCKER_BASE_DIR/jackett"
    "$DOCKER_BASE_DIR/qbittorrent"
    "$DOCKER_BASE_DIR/nastools"
    "$MEDIA_BASE_DIR/Movie"
    "$MEDIA_BASE_DIR/Tv"
    "$MEDIA_BASE_DIR/Link/Movie"
    "$MEDIA_BASE_DIR/Link/Tv"
)
for dir in "${dirs[@]}"; do
    if [ ! -d "$dir" ]; then
        echo "创建目录: $dir"
        if ! mkdir -p "$dir"; then
            echo "错误：无法创建目录 $dir（请检查权限）"
            exit 1
        fi
        # 确保目录权限正确
        chown -R "$PUID:$PGID" "$dir" 2>/dev/null
    fi
done

# 生成 docker-compose.yml（优化变量引用）
echo "生成配置文件..."
cat > "$COMPOSE_FILE" << EOF
version: '3.8'

services:
  jackett:
    image: linuxserver/jackett:latest
    container_name: jackett
    restart: always
    ports:
      - "$JACKETT_PORT:9117"
    environment:
      - PUID=$PUID
      - PGID=$PGID
      - TZ=Asia/Shanghai
    volumes:
      - "$DOCKER_BASE_DIR/jackett:/config"
    networks:
      - nas-network
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:9117"]
      interval: 30s
      timeout: 10s
      retries: 3

  qbittorrent:
    image: linuxserver/qbittorrent:latest
    container_name: qbittorrent
    restart: always
    ports:
      - "$QBITTORRENT_WEBUI_PORT:8080"
      - "6881:6881"
      - "6881:6881/udp"
    environment:
      - PUID=$PUID
      - PGID=$PGID
      - TZ=Asia/Shanghai
      - WEBUI_PORT=8080
    volumes:
      - "$DOCKER_BASE_DIR/qbittorrent:/config"
      - "$MEDIA_BASE_DIR:/media"
    depends_on:
      - jackett
    networks:
      - nas-network
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080"]
      interval: 30s
      timeout: 10s
      retries: 3

  nastools:
    image: hsuyelin/nas-tools
    container_name: nastools
    restart: always
    ports:
      - "$NASTOOLS_PORT:3000"
    environment:
      - PUID=$PUID
      - PGID=$PGID
      - TZ=Asia/Shanghai
      - AUTO_UPDATE=true
      - RUN_MODE=release
    volumes:
      - "$DOCKER_BASE_DIR/nastools:/config"
      - "$MEDIA_BASE_DIR:/media"
    depends_on:
      - jackett
      - qbittorrent
    networks:
      - nas-network
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000"]
      interval: 30s
      timeout: 10s
      retries: 3

networks:
  nas-network:
    driver: bridge
EOF

# 选择合适的docker-compose命令（优化检测逻辑）
if command -v docker-compose &>/dev/null; then
    COMPOSE_CMD="docker-compose"
elif docker compose version &>/dev/null; then
    COMPOSE_CMD="docker compose"
else
    echo "错误：未检测到docker-compose或docker compose"
    exit 1
fi

# 清理旧服务并启动新服务（增加执行反馈）
echo "清理旧服务实例..."
if ! $COMPOSE_CMD -f "$COMPOSE_FILE" down &>/dev/null; then
    echo "警告：清理旧服务失败，可能是首次部署"
fi

echo "启动服务（可能需要几分钟，取决于网络速度）..."
if ! $COMPOSE_CMD -f "$COMPOSE_FILE" up -d; then
    echo -e "\n❌ 服务启动失败"
    echo "请运行以下命令查看详细日志："
    echo "$COMPOSE_CMD -f \"$COMPOSE_FILE\" logs --tail=100"
    exit 1
fi

# 等待服务启动（增加健康检查等待）
echo -e "\n等待服务初始化（10秒）..."
sleep 10

# 检查服务状态
echo -e "\n服务状态检查："
$COMPOSE_CMD -f "$COMPOSE_FILE" ps

# 部署结果提示（优化输出信息）
echo -e "\n========================================="
echo "🎉 部署成功！"
echo "访问地址："
echo "Jackett:      http://$(hostname -I | awk '{print $1}'):$JACKETT_PORT"
echo "Qbittorrent:  http://$(hostname -I | awk '{print $1}'):$QBITTORRENT_WEBUI_PORT"
echo "NASTOOLS:     http://$(hostname -I | awk '{print $1}'):$NASTOOLS_PORT"
echo "========================================="
echo "使用的用户ID：PUID=$PUID，PGID=$PGID"
echo "管理命令："
echo "  查看日志：$COMPOSE_CMD -f \"$COMPOSE_FILE\" logs -f"
echo "  重启服务：$COMPOSE_CMD -f \"$COMPOSE_FILE\" restart"
echo "  停止服务：$COMPOSE_CMD -f \"$COMPOSE_FILE\" stop"
echo "  卸载服务：$COMPOSE_CMD -f \"$COMPOSE_FILE\" down && rm -f \"$COMPOSE_FILE\""
echo "========================================="